﻿using DDD.Core.CQRS;
using DDD.Core.Exceptions;
using DDD.Core.Exceptions.System;
using DDD.Core.Extensions;
using DDD.Domain.Abstract.DBContext;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace DDD.Domain.Abstract.Transactions
{
    /// <summary>
    /// 需要开启事务
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TResponse"></typeparam>
    public class TransactionBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
        where TRequest : notnull
    {
        private readonly DomainDBContext _domainDBContext;
        private readonly ILogger<TransactionBehavior<TRequest, TResponse>> _logger;

        public TransactionBehavior(DomainDBContext domainDBContext, ILogger<TransactionBehavior<TRequest, TResponse>> logger)
        {
            _domainDBContext = domainDBContext;
            _logger = logger;
        }

        public async Task<TResponse> Handle(TRequest request, RequestHandlerDelegate<TResponse> next, CancellationToken cancellationToken)
        {
            var isCommand = request.GetType().GetInterfaces()
                 .Any(c => c.IsGenericType && c.GetGenericTypeDefinition() == typeof(ICommand<,>));
            if (!isCommand) return await next();

            var requestTypeName = request.GetGenericTypeName();
            var response = default(TResponse);

            try
            {
                Guid transactionId;
                var strategy = _domainDBContext.Database.CreateExecutionStrategy();

                await strategy.ExecuteAsync(async () =>
                {
                    using var transaction = await _domainDBContext.BeginTransaction();
                    transactionId = transaction.TransactionId;

                    _logger.LogInformation($"开始处理事务：时间：{DateTime.Now}，transactionId:{transactionId},commandType:{requestTypeName},command:{request}");

                    using (_logger.BeginScope(new Dictionary<string, object>()
                    {
                        {"transactionId",transactionId }
                    }))
                    {
                        response = await next();
                        _logger.LogInformation($"开始提交事务：时间：{DateTime.Now}， transactionId ：{transactionId}, ,commandType:{requestTypeName},command:{request}");

                        //提交事务并发布所有的事件
                        await _domainDBContext.SaveChanegeAsync();

                        await _domainDBContext.CommitTransaction();
                    }
                });

                return response;
            }
            catch (Exception ex)
            {
                await _domainDBContext.RollbackTransaction();

                if (ex is UnSystemException)
                    throw ex;
                else
                {
                    _logger.LogError($"开始回滚事务：时间：{DateTime.Now}, ,commandType:{requestTypeName},command:{request}");

                    throw new TransactionErrorExpection(ex.Message, ex);
                }
            }
        }
    }
}
